package com.df.blueben.controller;

import cn.hutool.core.lang.UUID;
import com.df.blueben.common.BaseResponse;
import com.df.blueben.common.ResultUtils;
import com.df.blueben.exception.BusinessException;
import com.df.blueben.exception.ErrorCode;
import com.df.blueben.utils.OSSUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    OSSUploadUtil ossUploadUtil;
    @PostMapping("/file")
    public BaseResponse<String> upload(@RequestParam("file") MultipartFile file) {
        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = "uploads/" + UUID.randomUUID() + fileExtension;

            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 上传到OSS
            String fileUrl = ossUploadUtil.uploadFile(objectName, inputStream);

            return ResultUtils.success(fileUrl);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文件上传失败");
        }
    }
}
